﻿using System;
using System.IO;
using System.ServiceProcess;
using System.Text;

namespace WindowsService
{
    public partial class MyFirstService : ServiceBase
    {
        public MyFirstService()
        {
            this.InitializeComponent();
        }

        /// <summary>
        ///     写入文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="msg"></param>
        public void Log(string msg, string custompath = "")
        {
            try
            {
                var Dict = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
                if (!Directory.Exists(Dict))
                {
                    Directory.CreateDirectory(Dict);
                }
                var fileName = Dict + "\\log" + DateTime.Now.ToString("yyyy-MM-dd") + custompath + ".txt";
                byte[] myByte = Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + msg + "\r\n");
                using (FileStream fsWrite = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Write))
                {
                    fsWrite.Write(myByte, 0, myByte.Length);
                    fsWrite.Close();
                    fsWrite.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("异常:" + ex.Message);
            }
        }

        /// <summary>
        ///     写入文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="msg"></param>
        public void Log2(string msg, string custompath = "")
        {
            try
            {
                var Dict = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
                if (!Directory.Exists(Dict))
                {
                    Directory.CreateDirectory(Dict);
                }
                var fileName = Dict + "\\log" + DateTime.Now.ToString("yyyy-MM-dd") + custompath + ".txt";
                byte[] myByte = Encoding.UTF8.GetBytes(msg + "\r\n");
                using (FileStream fsWrite = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Write))
                {
                    fsWrite.Write(myByte, 0, myByte.Length);
                    fsWrite.Close();
                    fsWrite.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("异常:" + ex.Message);
            }
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.

            string msg = DateTime.Now + "OnStart";
            this.Log(msg);
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            string msg = DateTime.Now + "OnStop";
            this.Log(msg);
        }
    }
}